﻿using Newtonsoft.Json;
using RedisDemo.Entitys;
using RedisDemo.Redis.Base;
using RedisDemo.Service.IServices;
using RedisDemo.Service.Repository;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisDemo.Service.Service
{
    public class UserService : IUserService
    {
        private readonly IRepositoryWrapper _repository;
        private readonly RedisConfig _redis;

        public UserService(IRepositoryWrapper repository, RedisConfig redis)
        {
            _repository = repository;
            _redis = redis;
        }
        public async Task<Account> GetAllUsers(int id)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            string key = "user:" + id;
            string result = _redis.Get(key);
            Account users = new Account();
            if (!string.IsNullOrWhiteSpace(result))
            {
                users = JsonConvert.DeserializeObject<Account>(result);
                Console.WriteLine("缓存查询");

                #region 测试方法
                var List = new List<string>() { "user:4", "user:5", "user:6" };
                // await StringGetAsync();//获取单个key的值 测试
                //var Value= await StringGetAsyncList();//获取多个Key
                //var Value = await KeyRenameAsync("user:3", "user:4");//获取多个Key
                //var Count = await KeyDeleteAsync(List); //批量删除

                //使用Hash表
                //添加
                //var Value = await HashSetAsync<Account>("HashTable", "测试1", users);
                //await HashSetAsync<Account>("HashTable", "测试2", users);
                //await HashSetAsync<Account>("HashTable", "测试3", users);
                //var TheResult = await HashExistsAsync("HashTable", "测试3"); //判断是否存在
                //var TheResult = await HashDeleteAsync("HashTable", "测试3"); //移除Hash表的某个值
                //var Value = await HashDeleteAsync("HashTable", new List<RedisValue>() { "测试1", "测试2", "测试3" }); //移除Hash表的多个值
                //var Value = await HashGetAsync<Account>("HashTable", "测试3"); //获取Hash表中的值
                //var Values = await HashKeysAsync<Account>("HashTable");   //获取Hash表全部字段
                //var Values = await HashGetAllAsync<Account>("HashTable");  //获取Hash表全部

                //List使用
                //var TheResult = await ListRightPushAsync<Account>("List", users); //入队
                //var TheResult = await ListRightPopAsync<Account>("List"); //出队
                //var Count = await ListLengthAsync("List"); //获取集合中的数量
                //var Values = await ListRangeAsync<Account>("List"); //获取指定的List
                //var Count = await ListRemoveAsync<Account>("List", users, 0);//移除指定的值
                #endregion

            }
            else
            {
                users = _repository.User.GetUserById(id);
                await _redis.StringSetAsync("user:" + id, JsonConvert.SerializeObject(users), TimeSpan.FromDays(1));
                Console.WriteLine("接口查询");
            }
            stopwatch.Stop();
            TimeSpan timeSpan = stopwatch.Elapsed;
            Console.WriteLine($"用时:{timeSpan.TotalMilliseconds} 毫秒");

            return users;
        }

        #region 测试使用帮助

        //获取单个Key
        public async Task<string> StringGetAsync()
        {
            return await _redis.StringGetAsync("user:1");
        }

        //获取多个Key
        public async Task<RedisValue[]> StringGetAsyncList()
        {
            var List = new List<string>() { "user:1", "user:2", "user:3" };
            return await _redis.StringGetAsync(List);
        }

        //重命名Key
        public async Task<bool> KeyRenameAsync(string key, string newKey)
        {
            return await _redis.KeyRenameAsync(key, newKey);
        }

        //批量删除
        public async Task<long> KeyDeleteAsync(List<string> listKey)
        {
            return await _redis.KeyDeleteAsync(listKey);
        }

        //添加Hash
        public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t)
        {
            return await _redis.HashSetAsync(key, dataKey, t);
        }

        // 判断某个数据是否已经被缓存
        public async Task<bool> HashExistsAsync(string key, string dataKey)
        {
            return await _redis.HashExistsAsync(key, dataKey);
        }
        //移除Hash表中的某个值
        public async Task<bool> HashDeleteAsync(string key, string dataKey)
        {
            return await _redis.HashDeleteAsync(key, dataKey);
        }
        //移除Hash表中的多个值
        public async Task<long> HashDeleteAsync(string key, List<RedisValue> dataKeys)
        {
            return await _redis.HashDeleteAsync(key, dataKeys);
        }
        //从Hash表中获取数据
        public async Task<T> HashGetAsync<T>(string key, string dataKey)
        {
            return await _redis.HashGetAsync<T>(key, dataKey);
        }
        //获取Hash表全部字段
        public async Task<List<string>> HashKeysAsync<T>(string key)
        {
            return await _redis.HashKeysAsync<T>(key);
        }
        //获取Hash表全部
        public async Task<HashEntry[]> HashGetAllAsync<T>(string key)
        {
            return await _redis.HashGetAllAsync<T>(key);
        }

        //List入队
        public async Task<long> ListRightPushAsync<T>(string key, T value)
        {
            return await _redis.ListRightPushAsync<T>(key, value);
        }
        //出队
        public async Task<T> ListRightPopAsync<T>(string key)
        {
            return await _redis.ListRightPopAsync<T>(key);
        }
        //获取集合中的数量
        public async Task<long> ListLengthAsync(string key)
        {
            return await _redis.ListLengthAsync(key);
        }
        //获取List
        public async Task<List<T>> ListRangeAsync<T>(string key)
        {
            return await _redis.ListRangeAsync<T>(key);
        }
        //移除指定ListId的内部List的值
        public async Task<long> ListRemoveAsync<T>(string key, T value, long count)
        {
            return await _redis.ListRemoveAsync<T>(key, value, count);
        }
        #endregion


        #region 发布订阅体验


        //发布
        public async Task Pub()
        {
            Console.WriteLine("请输入要发布向哪个通道？");
            var channel = Console.ReadLine();
            await Task.Delay(10);
            for (int i = 0; i < 100; i++)
            {
                var User = GenFu.GenFu.ListOf<Account>(1); //随机生成数据
                await _redis.PublishAsync(channel, User);
            }
        }
        //订阅
        public async Task Sub()
        {
            Console.WriteLine("请输入您要订阅哪个通道的信息？");
            var channelKey = Console.ReadLine();
            await _redis.SubscribeAsync(channelKey, (channel, message) =>
            {
                Console.WriteLine("接受到发布的内容为：" + message);
            });
            Console.WriteLine("您订阅的通道为：<< " + channelKey + " >> ! 请耐心等待消息的到来！！");
        }

        //取消订阅
        public async Task UnsubscribeAsync()
        {
            Console.WriteLine("请输入您要取消订阅通道的信息");
            var channelKey = Console.ReadLine();
            await _redis.UnsubscribeAsync(channelKey);
        }

        //取消全部订阅
        public async Task UnsubscribeAllAsync()
        {
            await _redis.UnsubscribeAllAsync();
            Console.WriteLine("取消全部订阅");
        }


        #endregion
    }
}
